import dayjs from 'dayjs';
import {
  BaseEntity,
  CreateDateColumn,
  DeleteDateColumn,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';

/**
 * 将 Date 对象格式化为 "YYYY-MM-DD HH:mm:ss" 字符串
 * @param date 要格式化的日期对象或时间戳。如果传入的是无效日期
 * @returns 格式化后的日期字符串(YYYY-MM-DD HH:mm:ss)
 */
const formatDate = (date: Date | null) => {
  return date && date instanceof Date
    ? dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    : date;
};

export abstract class CommonEntity extends BaseEntity {
  @PrimaryGeneratedColumn('uuid', {
    comment: '唯一标识符',
  })
  id: string;

  @CreateDateColumn({
    transformer: {
      to: (value: Date) => value,
      from: (value: Date) => formatDate(value),
    },
    nullable: false,
    type: 'datetime',
    comment: '创建时间',
    name: 'create_date',
  })
  createDate: string;

  @UpdateDateColumn({
    transformer: {
      to: (value: Date) => value,
      from: (value: Date) => formatDate(value),
    },
    nullable: false,
    type: 'datetime',
    comment: '最后修改时间',
    name: 'update_date',
  })
  updateDate: string;

  @DeleteDateColumn({
    transformer: {
      to: (value: Date | null) => value,
      from: (value: Date | null) => formatDate(value),
    },
    nullable: true,
    type: 'datetime',
    comment: '删除时间',
    name: 'delete_date',
    select: false,
  })
  deleteDate?: string | null;
}
